package demo.orm;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author : GuoFei
 * @date : 2019/1/22 11:22
 */
public class JavaFileUtils {

    private static Logger log = LoggerFactory.getLogger(JavaFileUtils.class);

    /**
     * 创建java属性
     *
     * @param column    列名
     * @param convertor 转换器
     * @return java文件内容
     */
    public static JavaFieldGetSet createFieldGetSetSRC(ColumnInfo column, TypeConvertor convertor) {
        JavaFieldGetSet gs = new JavaFieldGetSet();
        String javaFiledType = convertor.databaseType2JavaType(column.getDataType());
        String columnName = StringUtils.underlineToSmallCamel(column.getName());
        log.debug("匹配字段：name：" + column.getName() + " -> " + columnName + "  ||  type：" + column.getDataType() + " -> " + javaFiledType);
        gs.setFieldInfo("\tprivate " + javaFiledType + " " + columnName + ";\n");
        //生成getter
        StringBuilder getSrc = new StringBuilder();
        getSrc.append("\tpublic " + javaFiledType + " get" + StringUtils.underlineToBigCamel(column.getName()) + "(){\n");
        getSrc.append("\t\treturn " + columnName + ";\n");
        getSrc.append("\t}\n");
        gs.setGetInfo(getSrc.toString());
        //生成setter
        StringBuilder setSrc = new StringBuilder();
        setSrc.append("\tpublic void set" + StringUtils.underlineToBigCamel(column.getName()) + "(" + javaFiledType + " " + columnName + "){\n");
        setSrc.append("\t\tthis." + columnName + "=" + columnName + ";\n");
        setSrc.append("\t}\n");
        gs.setSetInfo(setSrc.toString());
        return gs;
    }

    /**
     * 更新表结构
     */
    public static void updateJavaPOFile() {
        log.info("更新表结构");
        Map<String, TableInfo> tables = TableContext.tables;
        for (TableInfo tableInfo : tables.values()) {
            createJavaPoFile(tableInfo, new SqlServerTypeConvertor());
        }
    }

    /**
     * 创建javaPOJO文件
     *
     * @param tableInfo 表名
     * @param convertor 转换器
     */
    public static void createJavaPoFile(TableInfo tableInfo, TypeConvertor convertor) {
        //获取源码
        String src = createJavaSrc(tableInfo, convertor);
        String srcPath = DBManage.getConf().getSrcPath() + "/";
        //将包名转换为文件名，然后和srcPath拼接
        String packagePath = DBManage.getConf().getPoPackage().replace(".", "/");
        File f = new File(srcPath + packagePath);
        if (!f.exists()) {
            f.mkdirs();
        }
        BufferedWriter bw = null;
        try {
            //将源码写入文件
            String fileName = f.getAbsoluteFile() + "/" + StringUtils.underlineToBigCamel(tableInfo.getTableName()) + ".java";
            log.info("文件名称" + fileName);
            bw = new BufferedWriter(new FileWriter(fileName));
            bw.write(src);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static String createJavaSrc(TableInfo tableInfo, TypeConvertor convertor) {
        Map<String, ColumnInfo> columns = tableInfo.getColumns();
        List<JavaFieldGetSet> javaFields = new ArrayList<>();
        for (ColumnInfo columnInfo : columns.values()) {
            JavaFieldGetSet javaFieldGetSet = createFieldGetSetSRC(columnInfo, convertor);
            javaFields.add(javaFieldGetSet);
        }
        StringBuilder src = new StringBuilder();
        //生成package语句
        src.append("package " + DBManage.getConf().getPoPackage() + ";\n");
        //生成import语句
        src.append("import java.sql.*;\n");
        src.append("import java.util.*;\n\n");
        //生成类声明语句
        src.append("public class " + StringUtils.underlineToBigCamel(tableInfo.getTableName()) + "{\n");
        //生成属性列表
        for (JavaFieldGetSet javaFieldGetSet : javaFields) {
            src.append(javaFieldGetSet.getFieldInfo());
        }
        src.append("\n\n");
        //生成get方法列表
        for (JavaFieldGetSet javaFieldGetSet : javaFields) {
            src.append(javaFieldGetSet.getGetInfo());
        }
        src.append("\n\n");
        //生成set方法列表
        for (JavaFieldGetSet javaFieldGetSet : javaFields) {
            src.append(javaFieldGetSet.getSetInfo());
        }
        src.append("\n\n");
        //生成结束符
        src.append("}");
        return src.toString();
    }

}
